#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
   @Author: 叶建伟
   @Email: yejw46507@hundsun.com
   @Time: 2023/7/12 10:30
   @File: logCheck.py
   paramiko连接服务器，通过关键字获取指定日志行
"""

import paramiko


from DataTest.env import Env
from BladeFerm.Lib.Common import logger


def detect_errors(server='hsrcm-rcce-task',env=None, keyword='Caused', num_lines_before=20, num_lines_after=100):
    """
    读取服务日志：
    默认获取错误日志的前十行，以及后一百行
    """
    env = Env(env)
    logger.info(f'ip:{env.ip}  账号：{env.linux_user}  密码：{env.linux_pwd}')
    server = server_replace(server)
    log_file = f'/data/software/{server}/{server}/logs/app.log'
    command = f"grep -A {num_lines_after} -B {num_lines_before} -i '{keyword}' {log_file}"
    print(command)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(env.ip, username=env.linux_user, password=env.linux_pwd)
    stdin, stdout, stderr = ssh.exec_command(f'[ -f "{log_file}" ] && echo "1" || echo "0"')
    file_exists = stdout.read().strip().decode() == '1'
    if not file_exists:
        log_file = f'/opt/software/{server}/{server}/logs/app.log'
    stdin, stdout, stderr = ssh.exec_command(command)
    output = stdout.read().decode()
    ssh.close()

    error_lines = output.split('\n')
    errors = []
    errors.append(f"**ip地址:{env.ip}; **{log_file}** 错误日志 :")
    for line in error_lines:
        errors.append(line)
    print(errors)
    return errors


def server_replace(keyword):
    servers = ['hsrcm-amlps-server', 'hsrcm-amlcom-server', 'hsrcm-amlwl-server', 'hsrcm-amlcp-server',
               'hsrcm-amlcrs-server', 'hsrcm-pbs-server', 'hsrcm-pbs-task', 'hsrcm-rcce-task', 'hsrcm-message-server',
               'hsrcm-wfl-server']
    for key in servers:
        if keyword in key:
            return key


if __name__ == "__main__":
    """
    server:服务名称
    env:环境名称，目前支持oracle、mysql、xtoracle
    """
    server = 'amlcom'
    env = 'tdsql'
    detect_errors(server,env)


